<template>
    <div class="box">
        <div class="top" @click="openFilter">
               <span>{{ currentDateDisplay }}</span> 
                <img src="../assets/tb/down.png" alt="">
        </div>
        <div class="content">
            <div class="nav">
                <div class="nav_left" :class="{ nav_active: activeTab === 'expense' }" @click="activeTab = 'expense'">
                    <div class="come" :class="{ active: activeTab === 'expense' }">
                       <p> 支出</p>
                       <div class="num">{{ totalExpense.toFixed(2) }}</div>
                    </div>
                </div>
                <div class="nav_right" :class="{ nav_active: activeTab === 'income' }" @click="activeTab = 'income'">
                    <div class="payfor" :class="{ active: activeTab === 'income' }">
                        <p>收入</p>
                        <div class="num">{{ totalIncome.toFixed(2) }}</div>
                    </div>
                </div>
            </div>
            <div class="charts-container">
                <div v-if="currentTab === '本周'" id="lineChart" class="chart"></div>
                <div v-else id="pieChart" class="chart"></div>
            </div>
            <div v-if="showNoData" class="data">
                <img src="../assets/tb/zanwu.png" alt="">
                <p>暂无数据记录</p>
            </div>
            <div class="item_title">支出排行榜</div>
            <div class="cont_lb">
                <div v-for="(category, index) in categoryRanking" :key="index" class="item_cont">
                    <div class="iconf">
                        <svgIcon :iconName="category.icon" font-size="50px"></svgIcon>
                    </div>
                    <div class="cont_lb_top">
                        <span>{{ category.name }}</span>
                        <span>{{ category.count }}笔</span>
                        <span>{{ Number(category.percentage).toFixed(2) }}%</span>
                        <span class="span_money">{{ category.amount.toFixed(2) }}</span>
                    </div>
                    <div class="cont_jdt">
                        <div class="progress-bar" :style="{ width: category.percentage + '%' }"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <TabBar />

    <!-- 时间选择弹窗 -->
    <van-popup v-model:show="showFilter" position="bottom" round :style="{ height: '40%' }">
        <div class="filter-popup">
            <!-- 顶部操作栏 -->
            <div class="filter-header">
                <div class="cancel" @click="cancelFilter">取消</div>
                <div class="filter-tabs">
                    <div 
                        v-for="tab in ['按年', '按月', '本周']" 
                        :key="tab"
                        :class="['tab-item', { active: tempCurrentTab === tab }]"
                        @click="switchTab(tab)"
                    >
                        {{tab}}
                    </div>
                </div>
                <div class="confirm" @click="confirmFilter">确定</div>
            </div>

            <!-- 按年选择内容 -->
            <div v-if="tempCurrentTab === '按年'" class="year-picker">
                <van-picker
                    :columns="yearColumns"
                    @change="onYearChange"
                    :default-index="yearDefaultIndex"
                    :show-toolbar="false"
                />
            </div>

            <!-- 按月选择内容 -->
            <div v-if="tempCurrentTab === '按月'" class="month-picker">
                <div class="picker-container">
                    <van-picker
                        :columns="yearColumns"
                        @change="onYearChange"
                        :default-index="yearDefaultIndex"
                        :show-toolbar="false"
                    />
                    <van-picker
                        :columns="monthColumns"
                        @change="onMonthChange"
                        :default-index="monthDefaultIndex"
                        :show-toolbar="false"
                    />
                </div>
            </div>

            <!-- 本周选择内容 -->
            <div v-if="tempCurrentTab === '本周'" class="week-picker">
                <div class="week-range">{{ currentWeekRange }}</div>
            </div>
        </div>
    </van-popup>
</template>

<script>
import TabBar from '@/components/TabBar.vue';
import * as echarts from 'echarts';
import request from '../utils/request';
import { Popup, Picker } from 'vant';

export default {
    components: {
        TabBar,
        [Popup.name]: Popup,
        [Picker.name]: Picker
    },
    data() {
        return {
            bills: [],
            loading: false,
            error: '',
            lineChart: null,
            pieChart: null,
            activeTab: 'expense',
            showFilter: false,
            selectedYear: new Date().getFullYear(),
            selectedMonth: new Date().getMonth() + 1,
            yearDefaultIndex: 0,
            monthDefaultIndex: 0,
            currentWeekStart: null,
            currentWeekEnd: null,
            currentWeekDates: [],
            currentTab: '本周',
            tempCurrentTab: '本周',
            tempSelectedYear: null,
            tempSelectedMonth: null
        }
    },
    computed: {
        showNoData() {
            return !this.loading && !this.error && this.bills.length === 0;
        },
        currentDateDisplay() {
            if (this.currentTab === '本周') {
                return '本周';
            } else if (this.currentTab === '按年' && this.selectedYear) {
                return `${this.selectedYear}年`;
            } else if (this.currentTab === '按月' && this.selectedYear && this.selectedMonth) {
                return `${this.selectedYear}年${this.selectedMonth}月`;
            }
            return '本周';
        },
        currentWeekRange() {
            const { start, end } = this.getCurrentWeekDates();
            const startDate = this.formatDate(start);
            const endDate = this.formatDate(end);
            // 格式化为 MM/DD 格式
            const formatShortDate = (dateStr) => {
                const [year, month, day] = dateStr.split('-');
                return `${month}/${day}`;
            };
            return `${formatShortDate(startDate)}——${formatShortDate(endDate)}`;
        },
        yearColumns() {
            const currentYear = new Date().getFullYear();
            return Array.from({length: currentYear - 2019 + 1}, (_, i) => ({
                text: `${2019 + i}年`,
                value: 2019 + i
            }));
        },
        monthColumns() {
            return Array.from({length: 12}, (_, i) => ({
                text: `${i + 1}月`,
                value: i + 1
            }));
        },
        totalExpense() {
            try {
                let filteredBills = this.bills.filter(bill => bill.type === 'expense');
                
                // 根据选择的时间范围过滤数据
                if (this.currentTab === '本周' && this.currentWeekStart && this.currentWeekEnd) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate >= new Date(this.currentWeekStart) && 
                               billDate <= new Date(this.currentWeekEnd);
                    });
                } else if (this.currentTab === '按年' && this.selectedYear) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate.getFullYear() === this.selectedYear;
                    });
                } else if (this.currentTab === '按月' && this.selectedYear && this.selectedMonth) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate.getFullYear() === this.selectedYear && 
                               billDate.getMonth() + 1 === this.selectedMonth;
                    });
                }
                
                return filteredBills.reduce((sum, bill) => sum + (Number(bill.amount) || 0), 0);
            } catch (err) {
                console.error('计算总支出错误:', err);
                return 0;
            }
        },
        
        totalIncome() {
            try {
                let filteredBills = this.bills.filter(bill => bill.type === 'income');
                
                // 根据选择的时间范围过滤数据
                if (this.currentTab === '本周' && this.currentWeekStart && this.currentWeekEnd) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate >= new Date(this.currentWeekStart) && 
                               billDate <= new Date(this.currentWeekEnd);
                    });
                } else if (this.currentTab === '按年' && this.selectedYear) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate.getFullYear() === this.selectedYear;
                    });
                } else if (this.currentTab === '按月' && this.selectedYear && this.selectedMonth) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate.getFullYear() === this.selectedYear && 
                               billDate.getMonth() + 1 === this.selectedMonth;
                    });
                }
                
                return filteredBills.reduce((sum, bill) => sum + (Number(bill.amount) || 0), 0);
            } catch (err) {
                console.error('计算总收入错误:', err);
                return 0;
            }
        },
        categoryRanking() {
            try {
                // 获取当前类型（支出/收入）的所有账单
                let filteredBills = this.bills.filter(bill => bill.type === this.activeTab);
                
                // 根据选择的时间范围过滤数据
                if (this.currentTab === '本周' && this.currentWeekStart && this.currentWeekEnd) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate >= new Date(this.currentWeekStart) && 
                               billDate <= new Date(this.currentWeekEnd);
                    });
                } else if (this.currentTab === '按年' && this.selectedYear) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate.getFullYear() === this.selectedYear;
                    });
                } else if (this.currentTab === '按月' && this.selectedYear && this.selectedMonth) {
                    filteredBills = filteredBills.filter(bill => {
                        const billDate = new Date(bill.time);
                        return billDate.getFullYear() === this.selectedYear && 
                               billDate.getMonth() + 1 === this.selectedMonth;
                    });
                }

                // 计算总金额
                const totalAmount = filteredBills.reduce((sum, bill) => sum + (Number(bill.amount) || 0), 0);

                // 按类别分组并计算统计数据
                const categoryStats = filteredBills.reduce((acc, bill) => {
                    const category = bill.category;
                    if (!acc[category]) {
                        acc[category] = {
                            name: category,
                            amount: 0,
                            count: 0,
                            icon: bill.icon || 'icon-jiangjin'
                        };
                    }
                    acc[category].amount += Number(bill.amount) || 0;
                    acc[category].count += 1;
                    return acc;
                }, {});

                // 转换为数组并计算百分比
                const ranking = Object.values(categoryStats)
                    .map(category => ({
                        ...category,
                        percentage: totalAmount > 0 ? ((category.amount / totalAmount) * 100).toFixed(2) : '0.00'
                    }))
                    .sort((a, b) => b.amount - a.amount); // 按金额降序排序

                return ranking;
            } catch (err) {
                console.error('计算类别排行错误:', err);
                return [];
            }
        }
    },
    methods: {
        // 获取本周的日期范围
        getCurrentWeekDates() {
            const now = new Date();
            const today = now.getDay(); // 获取今天是周几（0-6，0表示周日）
            
            // 计算本周一的日期
            const monday = new Date(now);
            // 如果是周日，往前推6天；否则往前推到本周一
            const daysToMonday = today === 0 ? 6 : today - 1;
            monday.setDate(now.getDate() - daysToMonday);
            monday.setHours(0, 0, 0, 0);
            
            // 计算本周日的日期
            const sunday = new Date(monday);
            sunday.setDate(monday.getDate() + 6);
            sunday.setHours(23, 59, 59, 999);
            
            const dates = Array.from({length: 7}, (_, i) => {
                const date = new Date(monday);
                date.setDate(monday.getDate() + i);
                return this.formatDate(date);
            });

            // 打印日期数组，用于调试
            console.log('Week dates:', dates.map(date => {
                const d = new Date(date);
                const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                const dayIndex = d.getDay() === 0 ? 6 : d.getDay() - 1;
                return `${date} (${weekdays[dayIndex]})`;
            }));
            
            return { 
                start: monday, 
                end: sunday,
                dates
            };
        },

        // 格式化日期为 YYYY-MM-DD
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

        async fetchBills() {
            this.loading = true;
            this.error = '';
            
            try {
                const response = await request.get('/api/category/categories', null, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (Array.isArray(response.data)) {
                    this.bills = response.data.flatMap(item => {
                        if (!Array.isArray(item.data)) {
                            console.warn('item.data 不是数组:', item);
                            return [];
                        }
                        
                        return item.data.map(dataItem => ({
                            id: item.id,
                            _id: dataItem._id,
                            order: item.order,
                            time: dataItem.time || new Date().toISOString(),
                            type: item.type || 'expense',
                            amount: dataItem.value || 0,
                            category: item.name || '未分类',
                            icon: item.icon || 'icon-jiangjin'
                        }));
                    });
                    
                    // 设置本周日期范围
                    const { start, end, dates } = this.getCurrentWeekDates();
                    this.currentWeekStart = this.formatDate(start);
                    this.currentWeekEnd = this.formatDate(end);
                    this.currentWeekDates = dates;
                    
                    this.updateCharts();
                } else {
                    console.error('数据格式不正确:', response.data);
                    this.bills = [];
                    this.error = '数据格式不正确';
                }
            } catch (err) {
                console.error('获取账单数据失败:', err);
                this.error = '获取账单数据失败，请稍后重试';
                this.bills = [];
            } finally {
                this.loading = false;
            }
        },
        
        // 初始化图表
        initCharts() {
            // 等待 DOM 更新后再初始化图表
            this.$nextTick(() => {
                this.initChartInstances();
            });
        },

        // 初始化图表实例
        initChartInstances() {
            console.log('初始化图表实例');
            // 先销毁现有实例
            if (this.lineChart) {
                this.lineChart.dispose();
                this.lineChart = null;
            }
            if (this.pieChart) {
                this.pieChart.dispose();
                this.pieChart = null;
            }

            // 初始化折线图
            const lineChartDom = document.getElementById('lineChart');
            if (lineChartDom) {
                console.log('初始化折线图');
                this.lineChart = echarts.init(lineChartDom);
            }
            
            // 初始化饼图
            const pieChartDom = document.getElementById('pieChart');
            if (pieChartDom) {
                console.log('初始化饼图');
                this.pieChart = echarts.init(pieChartDom);
            }
            
            // 监听窗口大小变化
            window.addEventListener('resize', () => {
                this.lineChart?.resize();
                this.pieChart?.resize();
            });
        },

        // 切换标签
        switchTab(tab) {
            console.log('切换标签:', tab);
            this.tempCurrentTab = tab;
            
            if (tab === '本周') {
                this.tempSelectedYear = null;
                this.tempSelectedMonth = null;
                const { start, end, dates } = this.getCurrentWeekDates();
                this.currentWeekStart = this.formatDate(start);
                this.currentWeekEnd = this.formatDate(end);
                this.currentWeekDates = dates;
            }
        },

        // 年份选择变化
        onYearChange(value) {
            console.log('年份选择变化:', value);
            this.tempSelectedYear = value.selectedValues[0];
            this.yearDefaultIndex = value.selectedIndexes[0];
            
            // 如果当前是按月标签，重置月份选择为当前月份
            if (this.tempCurrentTab === '按月') {
                this.tempSelectedMonth = new Date().getMonth() + 1;
                const monthIndex = this.monthColumns.findIndex(
                    month => month.value === this.tempSelectedMonth
                );
                this.monthDefaultIndex = monthIndex >= 0 ? monthIndex : 0;
            }
        },

        // 月份选择变化
        onMonthChange(value) {
            console.log('月份选择变化:', value);
            this.tempSelectedMonth = value.selectedValues[0];
            this.monthDefaultIndex = value.selectedIndexes[0];
        },

        // 打开筛选弹窗时初始化临时值
        openFilter() {
            this.tempCurrentTab = this.currentTab;
            this.tempSelectedYear = this.selectedYear;
            this.tempSelectedMonth = this.selectedMonth;
            
            // 设置默认年份索引
            if (this.tempSelectedYear) {
                const yearIndex = this.yearColumns.findIndex(
                    year => year.value === this.tempSelectedYear
                );
                this.yearDefaultIndex = yearIndex >= 0 ? yearIndex : 0;
            }
            
            // 设置默认月份索引
            if (this.tempSelectedMonth) {
                const monthIndex = this.monthColumns.findIndex(
                    month => month.value === this.tempSelectedMonth
                );
                this.monthDefaultIndex = monthIndex >= 0 ? monthIndex : 0;
            }
            
            this.showFilter = true;
        },

        // 确认筛选
        confirmFilter() {
            console.log('确认筛选时的状态:', {
                currentTab: this.tempCurrentTab,
                selectedYear: this.tempSelectedYear,
                selectedMonth: this.tempSelectedMonth
            });
            
            // 应用临时值到实际筛选值
            this.currentTab = this.tempCurrentTab;
            this.selectedYear = this.tempSelectedYear;
            this.selectedMonth = this.tempSelectedMonth;
            
            this.showFilter = false;
            
            // 根据当前标签类型更新图表
            if (this.currentTab === '本周') {
                const { start, end, dates } = this.getCurrentWeekDates();
                this.currentWeekStart = this.formatDate(start);
                this.currentWeekEnd = this.formatDate(end);
                this.currentWeekDates = dates;
            }
            
            // 确保在DOM更新后初始化图表
            this.$nextTick(() => {
                this.initChartInstances();
                this.updateCharts();
            });
        },

        // 取消筛选
        cancelFilter() {
            // 重置临时值
            this.tempCurrentTab = this.currentTab;
            this.tempSelectedYear = this.selectedYear;
            this.tempSelectedMonth = this.selectedMonth;
            this.showFilter = false;
        },

        updateCharts() {
            console.log('更新图表，当前模式:', this.currentTab, '当前类型:', this.activeTab);
            // 确保图表实例存在
            if (!this.lineChart && !this.pieChart) {
                console.log('图表实例不存在，重新初始化');
                this.initChartInstances();
            }

            try {
                // 获取所有类别
                const categories = [...new Set(this.bills
                    .filter(bill => bill.type === this.activeTab)
                    .map(bill => bill.category))].filter(Boolean);
                
                console.log('过滤后的类别:', categories);
                
                if (categories.length === 0) {
                    console.log('没有可用的类别数据');
                    return;
                }

                // 生成随机颜色数组
                const generateColors = (count) => {
                    const colors = [];
                    for (let i = 0; i < count; i++) {
                        const hue = (i * 137.5) % 360;
                        colors.push(`hsl(${hue}, 70%, 65%)`);
                    }
                    return colors;
                };

                if (this.currentTab === '本周') {
                    // 使用已缓存的日期数组
                    const dates = this.currentWeekDates;
                    
                    // 过滤出本周有数据的类别
                    const categoriesWithData = categories.filter(category => {
                        return dates.some(date => {
                            return this.bills.some(bill => 
                                bill.category === category && 
                                bill.type === this.activeTab &&
                                bill.time.startsWith(date)
                            );
                        });
                    });
                    
                    console.log('本周有数据的类别:', categoriesWithData);
                    
                    // 更新折线图
                    if (this.lineChart) {
                        console.log('更新折线图');
                        this.lineChart.setOption({
                            title: {
                                text: this.activeTab === 'expense' ? '各类别支出趋势' : '各类别收入趋势',
                                left: 'center',
                                top: 20,
                                textStyle: {
                                    fontSize: 28
                                }
                            },
                            tooltip: {
                                trigger: 'axis',
                                formatter: function(params) {
                                    let result = params[0].axisValue + '<br/>';
                                    params.forEach(param => {
                                        result += param.seriesName + ': ' + param.value.toFixed(2) + '<br/>';
                                    });
                                    return result;
                                },
                                textStyle: {
                                    fontSize: 24
                                }
                            },
                            legend: {
                                data: categoriesWithData,
                                bottom: 20,
                                type: 'scroll',
                                pageButtonPosition: 'end',
                                textStyle: {
                                    fontSize: 24
                                },
                                itemGap: 20,
                                itemWidth: 15,
                                itemHeight: 15
                            },
                            grid: {
                                top: 80,
                                left: 50,
                                right: 50,
                                bottom: 100,
                                containLabel: true
                            },
                            xAxis: {
                                type: 'category',
                                data: dates,
                                axisLabel: {
                                    interval: 0,
                                    fontSize: 24,
                                    margin: 15,
                                    formatter: (value) => {
                                        const date = new Date(value);
                                        const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                                        const dayIndex = date.getDay() === 0 ? 6 : date.getDay() - 1;
                                        return weekdays[dayIndex];
                                    }
                                },
                                axisLine: {
                                    lineStyle: {
                                        width: 2
                                    }
                                },
                                axisTick: {
                                    show: false
                                }
                            },
                            yAxis: {
                                type: 'value',
                                name: '金额',
                                nameTextStyle: {
                                    fontSize: 24,
                                    padding: [0, 0, 0, 40]
                                },
                                axisLabel: {
                                    fontSize: 24,
                                    margin: 15
                                },
                                axisLine: {
                                    show: true,
                                    lineStyle: {
                                        width: 2
                                    }
                                },
                                axisTick: {
                                    show: false
                                },
                                splitLine: {
                                    lineStyle: {
                                        type: 'dashed'
                                    }
                                }
                            },
                            series: categoriesWithData.map((category, index) => ({
                                name: category,
                                type: 'line',
                                symbol: 'circle',
                                symbolSize: 8,
                                data: dates.map(date => {
                                    return this.bills
                                        .filter(bill => 
                                            bill.category === category && 
                                            bill.type === this.activeTab &&
                                            bill.time.startsWith(date)
                                        )
                                        .reduce((sum, bill) => sum + (Number(bill.amount) || 0), 0);
                                }),
                                itemStyle: {
                                    color: generateColors(categoriesWithData.length)[index]
                                },
                                lineStyle: {
                                    width: 3
                                }
                            }))
                        });
                    }
                } else {
                    console.log('准备更新饼图');
                    // 按年或按月模式，显示饼图
                    let filteredBills = this.bills.filter(bill => bill.type === this.activeTab);
                    
                    // 根据选择的时间范围过滤数据
                    if (this.currentTab === '按年' && this.selectedYear) {
                        console.log('按年过滤数据:', this.selectedYear);
                        filteredBills = filteredBills.filter(bill => {
                            const billDate = new Date(bill.time);
                            return billDate.getFullYear() === this.selectedYear;
                        });
                    } else if (this.currentTab === '按月' && this.selectedYear && this.selectedMonth) {
                        console.log('按月过滤数据:', this.selectedYear, this.selectedMonth);
                        filteredBills = filteredBills.filter(bill => {
                            const billDate = new Date(bill.time);
                            return billDate.getFullYear() === this.selectedYear && 
                                   billDate.getMonth() + 1 === this.selectedMonth;
                        });
                    }

                    // 准备饼图数据
                    const pieData = categories.map((category, index) => {
                        const amount = filteredBills
                            .filter(bill => bill.category === category)
                            .reduce((sum, bill) => sum + (Number(bill.amount) || 0), 0);
                        return {
                            value: amount,
                            name: category,
                            itemStyle: {
                                color: generateColors(categories.length)[index]
                            }
                        };
                    }).filter(item => item.value > 0); // 只显示有数据的类别
                    
                    if (pieData.length === 0) {
                        console.log('没有可用的饼图数据');
                        return;
                    }
                    
                    console.log('饼图数据:', pieData);
                    
                    // 计算总金额用于百分比显示
                    const total = pieData.reduce((sum, item) => sum + item.value, 0);
                    
                    // 更新饼图
                    if (this.pieChart) {
                        console.log('设置饼图配置');
                        this.pieChart.setOption({
                            title: {
                                text: this.activeTab === 'expense' ? '各类别支出占比' : '各类别收入占比',
                                left: 'center',
                                top: 10,
                                textStyle: {
                                    fontSize: 28
                                }
                            },
                            tooltip: {
                                trigger: 'item',
                                formatter: function(params) {
                                    const percentage = ((params.value / total) * 100).toFixed(1);
                                    return `${params.name}<br/>金额: ${params.value.toFixed(2)}<br/>占比: ${percentage}%`;
                                },
                                textStyle: {
                                    fontSize: 24
                                }
                            },
                            legend: {
                                orient: 'horizontal',
                                left: 'center',
                                bottom: 20,
                                type: 'scroll',
                                textStyle: {
                                    fontSize: 24
                                },
                                formatter: function(name) {
                                    const item = pieData.find(d => d.name === name);
                                    if (item) {
                                        const percentage = ((item.value / total) * 100).toFixed(1);
                                        return `${name} (${percentage}%)`;
                                    }
                                    return name;
                                },
                                itemGap: 20,
                                itemWidth: 15,
                                itemHeight: 15,
                                pageButtonPosition: 'end',
                                pageButtonGap: 5,
                                pageIconSize: 12,
                                pageTextStyle: {
                                    fontSize: 24
                                }
                            },
                            series: [
                                {
                                    name: this.activeTab === 'expense' ? '支出占比' : '收入占比',
                                    type: 'pie',
                                    radius: ['40%', '70%'],
                                    center: ['50%', '50%'],
                                    avoidLabelOverlap: true,
                                    itemStyle: {
                                        borderRadius: 10,
                                        borderColor: '#fff',
                                        borderWidth: 2
                                    },
                                    label: {
                                        show: true,
                                        formatter: '{b}\n{d}%',
                                        fontSize: 24
                                    },
                                    emphasis: {
                                        label: {
                                            show: true,
                                            fontSize: 28,
                                            fontWeight: 'bold'
                                        },
                                        itemStyle: {
                                            shadowBlur: 10,
                                            shadowOffsetX: 0,
                                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                        }
                                    },
                                    data: pieData
                                }
                            ]
                        });
                    } else {
                        console.log('饼图实例不存在');
                    }
                }
            } catch (error) {
                console.error('更新图表时出错:', error);
                this.error = '更新图表失败，请稍后重试';
            }
        }
    },
    watch: {
        activeTab() {
            console.log('切换类型:', this.activeTab);
            // 确保在DOM更新后更新图表
            this.$nextTick(() => {
                // 销毁现有图表实例
                if (this.lineChart) {
                    this.lineChart.dispose();
                    this.lineChart = null;
                }
                if (this.pieChart) {
                    this.pieChart.dispose();
                    this.pieChart = null;
                }
                
                // 重新初始化图表
                this.initChartInstances();
                this.updateCharts();
            });
        }
    },
    mounted() {
        this.initCharts();
        this.fetchBills();
    },
    beforeUnmount() {
        // 清理图表实例
        if (this.lineChart) {
            this.lineChart.dispose();
            this.lineChart = null;
        }
        if (this.pieChart) {
            this.pieChart.dispose();
            this.pieChart = null;
        }
        window.removeEventListener('resize', this.handleResize);
    }
}
</script>

<style lang="less" scoped>
    .box{
        width: 100vw;
        height: 100vh;
        background-color: #f5f5f5;
        .top{
            width: 100%;
            height: 120px;
            text-align: center;
            line-height: 120px;
            font-size: 35px;
            color: white;
        }
        .content{
            width: 100%;
            .nav{
                width: 100%;
                height: 130px;
                display: flex;
                transition: all 0.3s ease;
                .nav_active {
                    background-color: #fff;
                }
                .nav_left{
                    width: 50%;
                    height: 100%;
                    cursor: pointer;
                    
                    .come{
                       width: 100px;
                       height: 100%;
                       margin: 0 auto;
                       text-align: center;
                       margin-top: 30px;
                       transition: all 0.3s ease;
                       p{
                        padding-bottom: 5px;
                        font-size: 32px;
                       }
                       .num{
                        font-size: 30px;
                        color: #ff9bb7;
                        border-bottom: 5px solid #ff9bb7;
                        transition: all 0.3s ease;
                       }
                       &.active {
                           transform: scale(1.2);

                           .num {
                               font-weight: bold;
                               border-bottom-width: 6px;
                           }
                       }
                    }
                }
                .nav_right{
                    width: 50%;
                    height: 100%;
                    text-align: center;
                    cursor: pointer;
                    .payfor{
                        width: 100px;
                        height: 100%;
                        margin: 0 auto;
                        text-align: center;
                        transition: all 0.3s ease;
                       p{
                        margin-top: 30px;
                        padding-bottom: 5px;
                        font-size: 32px;
                       }
                       .num{
                        font-size: 30px;
                        color: #80e57f; 
                        border-bottom: 5px solid #80e57f;
                        transition: all 0.3s ease;
                       }
                       &.active {
                           transform: scale(1.2);
                           .num {
                               font-weight: bold;
                               border-bottom-width: 6px;
                           }
                       }
                    }
                }
            }
            .item_title{
                width: 100%;
                height: 50px;
                font-size: 32px;
                color: #b8b8b8;
                // text-align: center;
                padding-left: 30px;
                background-color: #fff;
                line-height: 50px;
            }
            .cont_lb {
                width: 100%;
                height: calc(100vh - 1075px);
                background-color: #fff;
                overflow-y: auto;
                .item_cont {
                    width: 100%;
                    padding: 0 40px;
                    height: 120px;
                    font-size: 28px;
                    position: relative;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    .iconf {
                        width: 50px;
                        height: 50px;
                        position: absolute;
                        left: 30px;
                        top: 45px;
                        margin-left: 0;
                    }
                    .cont_lb_top {
                        margin-left: 50px;
                        width: 100%;
                        display: flex;
                        align-items: center;
                        height: 60px;
                        line-height: 60px;
                        span {
                            display: block;
                            margin-left: 20px;
                        }
                        .span_money {
                            position: absolute;
                            color: #ff9bb7; 
                            font-size: 34px;
                            top:auto;
                            right: 40px;
                        }
                    }
                    .cont_jdt {
                        margin-left: 70px;
                        width: 600px;
                        height: 10px;
                        background-color: #c5c3c3;
                        border-radius: 5px;
                        margin-top: 10px;
                        overflow: hidden;
                        position: relative;
                        
                        .progress-bar {
                            position: absolute;
                            left: 0;
                            top: 0;
                            height: 100%;
                            background-color: #ff9bb7;
                            border-radius: 5px;
                            transition: width 0.8s ease-in-out;
                        }
                    }
                } 
            }
            .charts-container {
                width: 100%;
                padding: 20px;
                box-sizing: border-box;
                
                .chart {
                    width: 100%;
                    height: 600px;
                    margin-bottom: 20px;
                    background: #fff;
                    border-radius: 10px;
                    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                }
            }
            .data{
                width: 100%;
                height: 100%;
                img{
                    margin-left: 85px;
                }
                p{
                    width: 100%;
                    font-size: 35px;
                    color: #b8b8b8;
                    text-align: center;
                }
            }
        }
    }

    .filter-popup {
        height: 100%;
        display: flex;
        flex-direction: column;
        
        .filter-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #eee;
            
            .cancel, .confirm {
                font-size: 28px;
                color: #666;
                padding: 10px;
            }
            
            .confirm {
                color: #ff9bb7;
            }
            
            .filter-tabs {
                display: flex;
                gap: 30px;
                
                .tab-item {
                    font-size: 28px;
                    color: #666;
                    padding: 10px;
                    position: relative;
                    
                    &.active {
                        color: #ff9bb7;
                        font-weight: bold;
                        
                        &::after {
                            content: '';
                            position: absolute;
                            bottom: 0;
                            left: 50%;
                            transform: translateX(-50%);
                            width: 40px;
                            height: 4px;
                            background: #ff9bb7;
                            border-radius: 2px;
                        }
                    }
                }
            }
        }
        
        .year-picker, .month-picker {
            flex: 1;
            overflow: hidden;
            
            .picker-container {
                display: flex;
                height: 100%;
                justify-content: space-evenly;
            }
        }

        .week-picker {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            
            .week-range {
                font-size: 42px;
                color: #333;
                text-align: center;
            }
        }
    }

    // 覆盖 vant 样式
    :deep(.van-picker) {
        height: 100%;
        
        .van-picker-column {
            font-size: 42px;
        }
        
        .van-picker-column__item {
            color: #333;
            
            &--selected {
                color: #ff9bb7;
                font-weight: bold;
            }
        }
    }
</style>